package com.example.shop_2302.fg

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseFragment
import com.example.base.param.OrderDetail
import com.example.base.param.ParamPreOrder
import com.example.shop_2302.R
import com.example.shop_2302.adapter.CarAdapter
import com.example.shop_2302.databinding.FragmentCarBinding


class CarFragment : BaseFragment<FragmentCarBinding,CarViewModel>() {
    lateinit var carAdapter: CarAdapter
    //定义一个全局变量   用来判断是删除的单个，，还是进行的批量删除
    var flag = false//默认是单个删除的
    override fun initView() {
        carAdapter = CarAdapter()
        binding.rvCar.adapter = carAdapter
        binding.rvCar.layoutManager = LinearLayoutManager(context)
        //请求数据
        viewModel.car("true","10","1")
        //点击item上的控件
        carAdapter.addChildClickViewIds(R.id.car_cb,R.id.car_sub,R.id.car_add,R.id.car_delete)
        carAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.car_cb->{
                    //点击cb,对应的选中值 isCheck会发生变化  ----变为原来的相反的
                    carAdapter.data[position].isCheck = !carAdapter.data[position].isCheck
                }
                R.id.car_sub->{
                    //点击-，页面上num的值-1  判断当前是否变成了1 ---控件不可用    后台数据-1了
                    carAdapter.data[position].cartNum--
                    (carAdapter.getViewByPosition(position,R.id.car_num) as TextView).text = "${carAdapter.data[position].cartNum}"
                    if(carAdapter.data[position].cartNum==1){
                        (carAdapter.getViewByPosition(position,R.id.car_sub) as TextView).isEnabled = false
                    }
                    //更新后台
                    viewModel.updateCar(carAdapter.data[position].id,carAdapter.data[position].cartNum)
                    //viewModel.updateCar(-1,carAdapter.data[position].id)//7012的接口
                }
                R.id.car_add->{
                    //点击+，页面上num+1,同时 - 这个控件肯定是可用的   后台数据+1
                    carAdapter.data[position].cartNum++
                    (carAdapter.getViewByPosition(position,R.id.car_num) as TextView).text = "${carAdapter.data[position].cartNum}"
                    (carAdapter.getViewByPosition(position,R.id.car_sub) as TextView).isEnabled = true
                    //更新后台
                    viewModel.updateCar(carAdapter.data[position].id,carAdapter.data[position].cartNum)
                    //viewModel.updateCar(1,carAdapter.data[position].id)//7012的接口
                }
                R.id.car_delete->{
                    //删除后台  -页面上删除
                    viewModel.deleteCar(arrayOf(carAdapter.data[position].id))
                    carAdapter.data.removeAt(position)
                    carAdapter.notifyItemRemoved(position)//局部刷新，不会影响其他item
                    //carAdapter.notifyDataSetChanged()
                    //viewModel.deleteCar(carAdapter.data[position].id.toString())//7012的删除
                }
            }
            //无论点击哪个控件，下方金额和全选控件都会发生变化
            checkBottom()
        }

        //点击cball,修改上方recyclerView的选中状态  //选中状态监听器，  参数  控件  选中状态
        binding.cbAll.setOnCheckedChangeListener { buttonView, isChecked ->
            //必须写点击事件
            binding.cbAll.setOnClickListener {
                carAdapter.data.forEach {
                    it.isCheck = isChecked
                }
                carAdapter.notifyDataSetChanged()
                checkBottom()
            }
        }

        //点击管理，文字变成"取消"，对应布局显示取消的，  再次点击，文字变回”管理“，对应布局显示管理的
        binding.tvManage.setOnClickListener {
            if(binding.tvManage.text.toString() == "管理"){
                binding.tvManage.text = "取消"
                binding.llCancel.isVisible = true
                binding.llManage.isVisible = false
            }else{
                binding.tvManage.text = "管理"
                binding.llManage.isVisible = true
                binding.llCancel.isVisible = false
            }
        }
        //点击删除，实现批量删除
        binding.tvDelete.setOnClickListener {
            //判断是否存在选中的
            val list = mutableListOf<Boolean>()
            carAdapter.data.forEach {
                list.add(it.isCheck)
            }
            if(true in list){
                flag = true//记录当前删除方式为批量删除
                var ids = arrayOf<Int>()//用来存放选中的购物车id
                carAdapter.data.forEach{
                    if(it.isCheck){
                        ids +=it.id
                    }
                }
                viewModel.deleteCar(ids)//未达到局部刷新的效果
                //7012拼接ids
             /*   var ids1 = ""
                carAdapter.data.forEach {
                    if(it.isCheck){
                       if(ids1.length>0){
                           //不是第一个，需要在她的后边加“，”然后再加数据
                           ids1+=","
                       }
                        ids1+=it.id
                    }
                }
                viewModel.deleteCar(ids1)*/

            }else{
                ToastUtils.showLong("至少选择一种商品")
            }
        }

        //点击立即下单，跳转到 查看预下单界面
        binding.orderNow.setOnClickListener {
            //判断是否有选中的商品
            val list = mutableListOf<Boolean>()
            carAdapter.data.forEach {
                list.add(it.isCheck)
            }
            if(true in list){
                //有选中商品
                val paramPreOrder = ParamPreOrder()
                paramPreOrder.preOrderType = "shoppingCart"//购物车下单
                val orderlist = mutableListOf<OrderDetail>()
                carAdapter.data.forEach {
                    if(it.isCheck){
                        val orderDetail = OrderDetail()
                        orderDetail.shoppingCartId = it.id//购物车
                        orderlist.add(orderDetail)
                    }
                }
                paramPreOrder.orderDetails = orderlist

                viewModel.preOrder(paramPreOrder)
            }else{
                ToastUtils.showLong("至少选中一个商品")
            }
        }
    }

    private fun checkBottom() {
        //修改金额   修改选中状态  //记录选中的条数
        var total = 0
        var amount = 0f
        carAdapter.data.forEach {
            if(it.isCheck){
                total++
                amount+=it.cartNum*it.price.toFloat()
            }
        }
        binding.amountAll.text = "￥$amount"
        binding.cbAll.text = "全选($total)"
        binding.tvCount.text = "购物数量${carAdapter.data.size}"
        //修改选中状态 将data中数据进行判断 是否存在未选中   存在---false   不存在---true
        val list = mutableListOf<Boolean>()
        carAdapter.data.forEach {
            list.add(it.isCheck)
        }
        if(false in list){
            binding.cbAll.isChecked = false
        }else{
            binding.cbAll.isChecked = true
        }
    }

    override fun initData() {
        viewModel.carSuccess.observe(this){
            if(it.code==200){
                carAdapter.data.clear()
                carAdapter.data.addAll(it.data.list)
                carAdapter.notifyDataSetChanged()
                binding.tvCount.text = "购物数量${it.data.list.size}"
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.carFail.observe(this){
            ToastUtils.showLong(it)
        }
        viewModel.updateSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.deleteSuccess.observe(this){
           ToastUtils.showLong(it.message)
            if(it.code==200){
                if(flag){//////只有批量删除时，进行刷新
                    flag = false//将删除方式修改为单个删除
                    //刷新界面
                    viewModel.car("true","10","1")
                    //底部金额等也要发生变化
                    binding.cbAll.text = "全选(0)"
                    binding.amountAll.text = "￥0"
                }
            }
        }
        viewModel.deleteFail.observe(this){
            ToastUtils.showLong(it)
        }

        viewModel.preSuccess.observe(this){
            if(it.code==200){
                ARouter.getInstance().build("/app/CreateOrderActivity").withString("preOrderNo",it.data.preOrderNo).navigation()
            }
        }
    }

    override fun getViewModel(): Class<CarViewModel>  = CarViewModel::class.java

    override fun getLayout(): Int  = R.layout.fragment_car

}